package com.hundsun.cprs.yyt.gateway.service.trade.impl;

import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.gateway.vo.OrderItemVo;
import com.hundsun.cprs.yyt.gateway.vo.TradeMatchDetailVo;
import com.hundsun.cprs.yyt.service.common.dto.FundBatchRequest;
import com.hundsun.cprs.yyt.service.common.dto.UserAccountDTO;
import com.hundsun.cprs.yyt.service.common.enums.EnumFundBidCode;
import com.hundsun.cprs.yyt.service.common.service.RemoteTradeFundService;
import com.hundsun.cprs.yyt.service.common.service.RemoteUserService;
import com.hundsun.cprs.yyt.service.dilivery.enums.EnumDiliveryType;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsSpecs;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsStockLog;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsInfo;
import com.hundsun.cprs.yyt.service.goods.enums.EnumStockType;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsStockLogService;
import com.hundsun.cprs.yyt.service.order.domain.OrderItem;
import com.hundsun.cprs.yyt.service.order.dto.OrderInfo;
import com.hundsun.cprs.yyt.service.order.enums.EnumDeliveryMethod;
import com.hundsun.cprs.yyt.service.order.enums.EnumOrderSNCode;
import com.hundsun.cprs.yyt.service.order.enums.EnumsOrderStatus;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.service.rabbit.RoutingKeyConstants;
import com.hundsun.cprs.yyt.service.trade.domain.query.ReturnGoodsFlowQuery;
import com.hundsun.cprs.yyt.service.trade.dto.EntrustDeliveryRequest;
import com.hundsun.cprs.yyt.service.trade.enums.EnumEntustBSType;
import com.hundsun.cprs.yyt.service.trade.enums.EnumReturnGoodsFlowStatus;
import com.hundsun.cprs.yyt.service.trade.enums.EnumTradeEntrustStatus;
import com.hundsun.cprs.yyt.service.trade.enums.EnumTradeStatus;
import com.hundsun.cprs.yyt.service.trade.service.ReturnGoodsFlowService;
import com.hundsun.cprs.yyt.util.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hundsun.cprs.yyt.common.base.BaseService;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.enums.EnumCommonCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.gateway.request.EntrustDeliveryGoodsRequest;
import com.hundsun.cprs.yyt.gateway.request.EntrustReturnGoodsRequest;
import com.hundsun.cprs.yyt.gateway.request.TradeEntrustQueryRequest;
import com.hundsun.cprs.yyt.gateway.response.BaseResponse;
import com.hundsun.cprs.yyt.gateway.response.TradeEntrustListResponse;
import com.hundsun.cprs.yyt.gateway.response.TradeEntrustResponse;
import com.hundsun.cprs.yyt.gateway.service.trade.EntrustCommonService;
import com.hundsun.cprs.yyt.gateway.vo.TradeEntrustVo;
import com.hundsun.cprs.yyt.service.trade.domain.TradeEntrust;
import com.hundsun.cprs.yyt.service.trade.domain.query.TradeEntrustQuery;
import com.hundsun.cprs.yyt.service.trade.service.TradeEntrustService;
import com.hundsun.cprs.yyt.util.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class EntrustCommonServiceImpl extends BaseService implements EntrustCommonService {
    
    @Autowired
    private TradeEntrustService tradeEntrustService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ReturnGoodsFlowService flowService;

    @Override
    public TradeEntrustListResponse selectTradeEntrustList(TradeEntrustQueryRequest request) {
        TradeEntrustListResponse response = new TradeEntrustListResponse();
        try {
            Validate.notNull(request,"参数非法");
            Validate.notNull(request.getUserId(),"请刷新页面缓存");
            if (request.getGoodsId() != null){
                //由于前台页面上的挂售列表改成了成交列表，所以此处的查询商品的挂售列表功能屏蔽
                return response;
            }
            TradeEntrustQuery query = BeanUtils.transfrom(TradeEntrustQuery.class, request);
            query.setEntrustBs(EnumEntustBSType.SELL.getCode().toString());
            query.setEntrustStatus(null);
            query.setStatus(request.getEntrustStatus());
            //多状态集合查询转换
            statusArrayChansform(request,query);
            if (request.getUserId() != null){
                query.setOrderStr("DESC");//降序排列
            }
            tradeEntrustService.selectByPage(query);
            
            if (query.getTotalCount() > 0) {
                response.setTotalCount(query.getTotalCount());
                List<TradeEntrustVo> result = BeanUtils.batchTransform(TradeEntrustVo.class, query.getData());
                //填充订单项信息
                fillOrderItemInfo(result);
                response.setResult(result);
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;        
    }

    protected void statusArrayChansform(TradeEntrustQueryRequest request,TradeEntrustQuery query){
        if (request.getStatusArray()!= null && !request.getStatusArray().isEmpty()){
            String[] statusArray = StringUtils.split(request.getStatusArray(), ",");
            Integer[] statusList = new Integer[statusArray.length];
            for (int i=0;i<statusArray.length;i++) {
                statusList[i]=Integer.parseInt(statusArray[i]);
            }
            query.setStatusArray(statusList);
        }
    }

    @Override
    public TradeEntrustResponse getTradeEntrust(Long entrustId) {
        TradeEntrustResponse response = new TradeEntrustResponse();
        try {
            Validate.notNull(entrustId,"参数非法");
            TradeEntrust tradeEntrust = tradeEntrustService.getTradeEntrustById(entrustId);
            if (tradeEntrust != null) {
                //填充订单项信息
                TradeEntrustVo tradeEntrustVo = BeanUtils.transfrom(TradeEntrustVo.class, tradeEntrust);
                OrderInfo orderInfo = orderService.selectOrderInfoByOrderSn(tradeEntrustVo.getOrderSn());
                if (orderInfo != null){
                    tradeEntrustVo.setOrderItems(BeanUtils.batchTransform(OrderItemVo.class,orderInfo.getOrderItems()));
                }else{
                    //平台挂单数据，填充零售价和图片等信息
                    plateFormEntrustFillOrderInfo(tradeEntrustVo,tradeEntrust.getGoodsId().intValue());
                }
                //设置是否允许提货和退货标志
                setflag(tradeEntrustVo);
                response.setResult(tradeEntrustVo);
            }
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;   
    }

    protected void setflag(TradeEntrustVo tradeEntrustVo){
        if (tradeEntrustVo.getStatus().equals(EnumTradeStatus.CANCELED.getStatus())){
            //判断是否允许退货还要看是否存在待审核的申请记录
            ReturnGoodsFlowQuery query = new ReturnGoodsFlowQuery();
            query.setStatus(EnumReturnGoodsFlowStatus.WAIT_AUDIT.getCode());
            query.setEntrustNo(tradeEntrustVo.getEntrustNo());
            flowService.queryByPage(query);
            if (query.getTotalCount() > 0){
                tradeEntrustVo.setIsCanReturn("N");
                tradeEntrustVo.setIsCanDelivery("N");
            }else {
                tradeEntrustVo.setIsCanReturn("Y");
                tradeEntrustVo.setIsCanDelivery("Y");
            }
        }else {
            tradeEntrustVo.setIsCanDelivery("N");
            tradeEntrustVo.setIsCanReturn("N");
        }
    }
    /*@Override
    public BaseResponse reEntrust(Long userId, Long entrustId) {
        BaseResponse response = new BaseResponse();
        try {
            Validate.notNull(userId,"用户信息不能为空");
            Validate.notNull(entrustId,"挂售单信息不能为空");
            //1.查询挂售单信息
            TradeEntrust tradeEntrust = tradeEntrustService.getTradeEntrustById(entrustId);
            if (tradeEntrust == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1512.getErrorNo(),EnumBusinessCode.BUSINESS_1512.getErrorInfo());
            }
            //2.比较用户和挂售用户是否一致
            if (Long.compare(userId,tradeEntrust.getUserId())!=0){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1513.getErrorNo(),EnumBusinessCode.BUSINESS_1513.getErrorInfo());
            }
            //3.上报
            tradeEntrustService.entrust(tradeEntrust);
        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;   
    }*/

    @Override
    public BaseResponse applyDeliveryGoods(EntrustDeliveryGoodsRequest request) {
        BaseResponse response = new BaseResponse();
        try {
            Validate.notNull(request,"参数不能为空");
            Validate.notNull(request.getEntrustId(),"挂售单信息不能为空");
            Validate.notNull(request.getUserId(),"用户信息不能为空");
            Validate.notNull(request.getDiliveryId(),"提货地址信息不能为空");
            if (request.getDeliveryType().equals(EnumDeliveryMethod.SELFGET.ordinal())){
                Validate.notNull(request.getSeleGetName(),"自提人姓名不能为空");
                Validate.notNull(request.getSelfGetPhone(),"自提人手机号不能为空");
                Validate.notNull(request.getSelfGetTime(),"自提时间不能为空");
            }
            //1.获取挂售单信息
            TradeEntrust tradeEntrust = tradeEntrustService.getTradeEntrustById(request.getEntrustId());
            if (tradeEntrust == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1512.getErrorNo(),EnumBusinessCode.BUSINESS_1512.getErrorInfo());
            }
            //2.校验挂售单大类状态是否为已撤销
            if (!tradeEntrust.getStatus().equals(EnumTradeStatus.CANCELED.getStatus())){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1515.getErrorNo(),EnumBusinessCode.BUSINESS_1515.getErrorInfo());
            }
            //3.比较用户和挂售用户是否一致
            if (Long.compare(request.getUserId(),tradeEntrust.getUserId())!=0){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1513.getErrorNo(),EnumBusinessCode.BUSINESS_1513.getErrorInfo());
            }
            //4.判断该挂售单是否存在待审核的退货申请流水
            validateReturnGoodsFlow(tradeEntrust);
            //5.判断挂售单关联的订单是否存在，不存在则打回，不允许发货，兼容易亿通的迁移订单
            OrderInfo orderInfo = orderService.selectOrderInfoByOrderSn(tradeEntrust.getOrderSn());
            if (orderInfo == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1525.getErrorNo(),EnumBusinessCode.BUSINESS_1525.getErrorInfo());
            }
            EntrustDeliveryRequest entrustDeliveryRequest = BeanUtils.transfrom(EntrustDeliveryRequest.class,request);
            tradeEntrustService.applyDeliveryGoods(tradeEntrust,entrustDeliveryRequest);

        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;   
    }

    @Override
    public BaseResponse applyReturnGoods(EntrustReturnGoodsRequest request) {
        BaseResponse response = new BaseResponse();
        try {
            Validate.notNull(request,"参数不能为空");
            Validate.notNull(request.getEntrustId(),"挂售单信息不能为空");
            Validate.notNull(request.getUserId(),"用户信息不能为空");
            //1.获取挂售单信息
            TradeEntrust tradeEntrust = tradeEntrustService.getTradeEntrustById(request.getEntrustId());
            if (tradeEntrust == null){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1512.getErrorNo(),EnumBusinessCode.BUSINESS_1512.getErrorInfo());
            }
            //2.校验挂售单大类状态是否为已撤销
            if (!tradeEntrust.getStatus().equals(EnumTradeStatus.CANCELED.getStatus())){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1516.getErrorNo(),EnumBusinessCode.BUSINESS_1516.getErrorInfo());
            }
            //3.比较用户和挂售用户是否一致
            if (Long.compare(request.getUserId(),tradeEntrust.getUserId())!=0){
                throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1513.getErrorNo(),EnumBusinessCode.BUSINESS_1513.getErrorInfo());
            }
            //4.校验该挂售单是否已经申请退货
            validateReturnGoodsFlow(tradeEntrust);
            tradeEntrustService.returnGoods(tradeEntrust);

        } catch (IllegalArgumentException e) {
            response.setErrorNo(EnumBusinessCode.BUSINESS_1000.getErrorNo());
            response.setErrorInfo(e.getMessage());
        } catch (ServiceCodeException e) {
            response.setErrorNo(e.getErrorCode());
            response.setErrorInfo(e.getErrorDesc());
        } catch (Exception e) {
            logger.error("处理异常", e);
            response.setErrorNo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorNo());
            response.setErrorInfo(EnumCommonCode.COMMON_SERVER_ERROR.getErrorInfo());
        }
        return response;   
    }

    protected void validateReturnGoodsFlow(TradeEntrust tradeEntrust){
        ReturnGoodsFlowQuery query = new ReturnGoodsFlowQuery();
        query.setStatus(EnumReturnGoodsFlowStatus.WAIT_AUDIT.getCode());
        query.setEntrustNo(tradeEntrust.getEntrustNo());
        flowService.queryByPage(query);
        if (query.getTotalCount() > 0){
            throw new ServiceCodeException(EnumBusinessCode.BUSSINESS_1706.getErrorNo(),EnumBusinessCode.BUSSINESS_1706.getErrorInfo());
        }
    }

    protected void fillOrderItemInfo(List<TradeEntrustVo> tradeEntrustVoList){
        for (TradeEntrustVo tradeEntrustVo : tradeEntrustVoList){
            OrderInfo orderInfo = orderService.selectOrderInfoByOrderSn(tradeEntrustVo.getOrderSn());
            if (orderInfo != null){
                tradeEntrustVo.setOrderItems(BeanUtils.batchTransform(OrderItemVo.class,orderInfo.getOrderItems()));
            }else{
                //平台挂单数据，填充零售价和图片等信息
                plateFormEntrustFillOrderInfo(tradeEntrustVo,tradeEntrustVo.getGoodsId().intValue());
            }
        }
    }

    protected void plateFormEntrustFillOrderInfo(TradeEntrustVo tradeEntrustVo,int goodsId){
        //对于平台挂售的单子，是没有订单信息，此时需要填充商品的零售价作为委托单的挂售价
        GoodsInfo goodsInfo = goodsService.selectGoodsInfoById(goodsId);
        List<OrderItemVo> orderItemVoList = new ArrayList<>();
        if (goodsInfo != null){
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setGoodsName(goodsInfo.getGoodsName());
            orderItemVo.setCostPrice(goodsInfo.getCostPrice().longValue());
            orderItemVo.setThumbnail(goodsInfo.getImageList().get(0).getOriginalImageUrl());
            orderItemVoList.add(orderItemVo);
        }
        tradeEntrustVo.setOrderItems(orderItemVoList);
    }
}
